package com.legna.xyq.alert.service;

import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef;
import com.sun.jna.platform.win32.WinUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


@Service
public class AlertService {

    @Autowired
    private EmailService emailService;


    private Boolean switchOpen = true;
    private Boolean isSend = true;

    private List<String> receiveEmails = new ArrayList<>();



    @Scheduled(cron = "0 0/1 * * * ? ")
    public void openSend(){
        if (switchOpen){
            isSend = true;
        }
    }
    public Boolean switchSendFun(){
        switchOpen = !switchOpen;
        return switchOpen;
    }


    @Scheduled(cron = "0/1 * * * * ? ")
    public void alertData() {
        if (switchOpen){
            return;
        }
        User32 user32 = User32.INSTANCE;

        user32.EnumWindows(new WinUser.WNDENUMPROC() {
            @Override
            public boolean callback(WinDef.HWND hWnd, Pointer arg1) {
                char[] windowText = new char[512];
                user32.GetWindowText(hWnd, windowText, 512);
                String title = Native.toString(windowText);
                if (title.equals("网络错误")){
                    System.out.println("Window title: " + title);
                    sendMessage();
                }
                return true;
            }
        }, null);
    }


    public List<String> addReceiver(String addEmail){
        receiveEmails.add(addEmail);
        return receiveEmails;
    }

    public List<String> removeReceiver(String removeEmail){
        receiveEmails.removeIf(next -> next.equals(removeEmail));
        return receiveEmails;
    }

    public void sendMessage(){
        if (isSend){
            emailService.sendEmail("15067388403@163.com","15067388403@163.com","梦幻西游掉线提醒","有号离线，如果是顶号请忽略");
            for (String receiveEmail : receiveEmails) {
                try {
                    emailService.sendEmail("15067388403@163.com",receiveEmail,"梦幻西游掉线提醒","有号离线，如果是顶号请忽略");
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            isSend = false;
        }
    }
}
